/*
 * Copyright (C) 2011 Jake Wharton
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.timothy.fund.ui;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.sina.stock.data.SinaStockClient;
import com.sina.stock.data.SinaStockInfo;
import com.sina.stock.data.SinaStockInfo.ParseStockInfoException;
import com.timothy.fund.adapter.RepoAdaptor;
import com.timothy.fund.bean.Repo;
import com.timothy.fund.data.ParseXML;
import org.apache.commons.httpclient.HttpException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class RepoListActivity extends SherlockActivity {
	public static final String LOG_TAG = "StockAListActivity";
	
	public static int THEME = R.style.Theme_Sherlock;
	Context mContext;
	ListView repoListView;
	List<String> codeList;
	List<Repo> saList;

    List<Repo> valueList;
    RepoAdaptor adaptor ;

	private SinaStockClient mClient;
    private String message;

    private void initClient() {
    	mClient = SinaStockClient.getInstance();
    }
    
	public void getData(){
        codeList = ParseXML.getRepoCodeList(mContext);

		Map<String,Double> saMap = null; //code&info Map
		try {
			//获取证券代码和信息（key:代码 Value 信息）
            String[] array = new String[codeList.size()];
            codeList.toArray(array); // fill the array

			saMap = mClient.getStockPrice(array);

            saList = ParseXML.getRepoList(mContext);
            valueList = new ArrayList<Repo>();
            for (Repo repo : saList) {
                String code= repo.getCode();
                repo.setPrice(saMap.get(code));
                valueList.add(repo);
            }
		} catch (HttpException e) {
			Log.e(LOG_TAG,e.getMessage());
		} catch (IOException e) {
			Log.e(LOG_TAG,e.getMessage());
		} catch (ParseStockInfoException e) {
			Log.e(LOG_TAG,e.getMessage());
		}



    }
	
	public void displayData(){
	       //set List
        adaptor = new RepoAdaptor(mContext,valueList);
        repoListView = (ListView)findViewById(R.id.repo_listview);
        repoListView.setAdapter(adaptor);
//        repoListView.setOnItemClickListener(new OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
//                                    long arg3) {
//            }
//        });
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Used to put dark icons on light action bar
        menu.add("Refresh")
            .setIcon(R.drawable.ic_refresh)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //This uses the imported MenuItem from ActionBarSherlock
//        Toast.makeText(this, "Data refreshed!", Toast.LENGTH_SHORT).show();
        reLoadData();
        return true;
    }
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(RepoListActivity.THEME); //Used for theme switching in samples
        super.onCreate(savedInstanceState);
        setContentView(R.layout.repo);
        
        mContext = getApplicationContext();
        
        initClient();
        reLoadData();
    }
    
    public void reLoadData(){
    	new Thread(getDataRunnable).start();
    }
    
    private Runnable getDataRunnable = new Runnable(){
        @Override
        public void run() {
            try {
            	getData();
                message = "success";
            } catch (Exception e) {
            	Log.e(LOG_TAG,e.getMessage());
            	message = "fail";
			}
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }
            
    };
    
    //set picture
    private Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            myDialog.dismiss();
//            imageView.setImageBitmap(bitmap);
            Toast.makeText(RepoListActivity.this, message, Toast.LENGTH_SHORT).show();
            if("success".equalsIgnoreCase(message)){
            	displayData();
            }
        }
    };
 
}
